package co.fitstart.coach.web.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.utils.CollectionUtils;
import com.demo2do.core.utils.DateUtils;

import co.fitstart.coach.entity.rest.RestRule;
import co.fitstart.coach.entity.security.Login;
import co.fitstart.coach.service.CoachRestCalendarService;
import co.fitstart.coach.service.CourseService;
import co.fitstart.coach.service.CoursewareService;
import co.fitstart.coach.service.PrincipalService;
import co.fitstart.coach.service.WeeklyPlanService;
import co.fitstart.coach.web.resolver.Secure;
import co.fitstart.entity.coach.CoachRestCalendar;
import co.fitstart.entity.course.schedule.CourseSchedule;
import co.fitstart.entity.courseware.exercise.PlannedSchedule;
import co.fitstart.entity.courseware.fitnessgroup.Courseware;
import co.fitstart.entity.principal.Principal;

/**
 * 
 * @author lidan
 *
 */
@Controller
@RequestMapping("/course-schedules")
public class CourseController {
    
    private static final Logger logger = LoggerFactory.getLogger(CourseController.class);
    
    @Autowired
    private PrincipalService principalService;
    
    @Autowired
    private CourseService courseService;
    
    @Autowired
    private CoachRestCalendarService coachRestCalendarService;
    
    @Autowired
    private WeeklyPlanService weekPlanService;
    
    @Autowired
    private CoursewareService coursewareService;
    
    /**
     * List weekly course schedules
     * 
     * @param login
     * @param startDate
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ModelAndView list(@Secure Login login,
                             @RequestParam(value = "start", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate){
        
        ModelAndView modelAndView = new ModelAndView("course/course-schedule-list");
        
        Principal principal = principalService.load(Principal.class, login.getId());
        modelAndView.addObject("coachId", principal.getId().toString());
        
        RestRule restRule = new RestRule(startDate);

        Date monday = DateUtils.getFirstWeekDay(restRule.getStartDate());
        
        // get weekly course schedule list
        List<CourseSchedule> schedules = courseService.getWeeklyCourseSchedule(principal, monday);
//        List<CourseSchedule> schedules = new ArrayList<CourseSchedule>();
//        schedules.addAll(result);
//        for(CourseSchedule courseSchedule : result) {
//            String[] arr = courseSchedule.getOccurHour().split(":");
//            if(arr[1].equals("00")) {
//                CourseSchedule schedule = new CourseSchedule(courseSchedule.getCourseRound(), courseSchedule);
//                schedules.add(schedule.editHour(arr[0] + ":30"));
//            } else if(arr[1].equals("30")) {
//                CourseSchedule schedule = new CourseSchedule(courseSchedule.getCourseRound(), courseSchedule);
//                int hour = Integer.parseInt(arr[0]) + 1;
//                schedules.add(schedule.editHour(Integer.valueOf(hour) + ":00"));
//            }
//        }
        modelAndView.addObject("schedules", CollectionUtils.constructMapValuesFromList(schedules, "dayhour"));
        
        List<CoachRestCalendar> restSchedules = coachRestCalendarService.getWeeklyCoachRestCalendar(principal, restRule.getStartDate());
        modelAndView.addObject("restSchedules", CollectionUtils.constructMapValuesFromList(restSchedules, "hour"));

        // put into modelAndView
        modelAndView.addObject("today", restRule.getToday());
        modelAndView.addObject("thisWeek", restRule.getThisWeek());
        
        modelAndView.addObject("lastWeek", restRule.getLastWeek());
        modelAndView.addObject("nextWeek", restRule.getNextWeek()); 
        
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = simpleDateFormat.format(restRule.getToday());
        modelAndView.addObject("currentTime", DateUtils.parseDate(date, "yyyy-MM-dd"));
        
        return modelAndView;
    }
    
    /**
     * View course schedule by day and hour
     * 
     * @param login
     * @param day
     * @param hour
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = {"day", "hour"})
    public ModelAndView view(@Secure Login login,
                             @RequestParam("day") @DateTimeFormat(pattern = "yyyy-MM-dd") Date day,
                             @RequestParam("hour") String hour){
        
        ModelAndView modelAndView = new ModelAndView("course/course-schedule-view");
        
        Principal principal = principalService.load(Principal.class, login.getId());
        
        logger.trace("view course schedule by day " + day + " and hour " + hour + " for coach " + principal.getName());

        List<CourseSchedule> courseSchedules = courseService.getCourseSchedule(principal, day, hour);
        modelAndView.addObject("courseSchedules", courseSchedules);
        
        if(!courseSchedules.isEmpty()) {
            PlannedSchedule plannedSchedule = weekPlanService.getPlannedSchedule(courseSchedules.get(0));
            List<Courseware> coursewares = coursewareService.listCourseWares(courseSchedules.get(0));
            
            modelAndView.addObject("plannedSchedule", plannedSchedule);
            modelAndView.addObject("coursewares", coursewares);
        }
        
        return modelAndView;
    }

}
